import { PointEnum, pointsManager } from '@/common/preview';
import { makeId } from '@/common/utils';
import { surfProcess } from '@/domain';
import { THREE } from '@amcax/web-render';
import { Box } from 'nextcae-base/src/dialogs/component/Box';
import { FormContent } from 'nextcae-base/src/dialogs/component/FormContent';
import { useState } from 'react';
import { schema, uiSchema } from '../../data';
import { excelType, TableData } from '../../type';
import { ButtonPointsGroups } from './ButtonTableGroups';
import { TableComponent } from './TableDropDownComponent';
import { Footer } from './TableFooter';

export function TableCsvComponentDialog(props: excelType) {
  const [uploadTableData, setUploadTableData] = useState([]);
  const [newTableData, setNewTableData] = useState<TableData[]>([]);
  const [formData, setFormData] = useState<any>({
    Selection: { source: [] },
  });

  const handleImport = (e) => {
    const fileInput = e.target; // 这是input元素
    const file = fileInput.files[0]; // 获取选择的文件
    if (!file) return;
    // 文件解析数据方法
    const reader = new FileReader();
    reader.onload = (readerEvent) => {
      const content = String(readerEvent.target?.result);
      csvToTableData(content);
    };
    reader.readAsText(file);
  };
  // 将 txt/csv 转成 tableData 类型
  const csvToTableData = (csv) => {
    // 校验数据格式
    const lines = csv.split(/\r\n|\n/).filter((line) => line.trim() !== '');
    // 表格数据
    const tableDataArray: TableData[] = [];
    lines.forEach((item, index) => {
      const line = item.split(',');
      const tableData: TableData = {
        key: index + 1,
        x: Number(line[0]),
        y: Number(line[1]),
        z: Number(line[2]),
      };
      tableDataArray.push(tableData);
    });
    setUploadTableData(tableDataArray);
  };

  // 导出csv
  const handleExport = () => {
    if (newTableData.length === 0) {
      return;
    }
    const rows = newTableData
      .map((item) => {
        return `${item.x ?? ''},${item.y ?? ''},${item.z ?? ''}`;
      })
      .join('\n');

    const blob = new Blob([rows], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'points.csv';
    link.click();
  };

  // 删除所有行
  const handleDeleteAll = () => {
    pointsManager().removePoints();
    setUploadTableData([]); // 清空上传的数据（如果有）
    setNewTableData([{ key: '1', x: null, y: null, z: null }]); // 重置为一行空数据
  };

  // 数据发生改变
  const handleDataChange = (data: TableData[]) => {
    // data 筛选出不为空的行
    const newData = data.filter(
      (item) => item.x !== null && item.y !== null && item.z !== null,
    );
    // 渲染点
    const validCoordinateData = newData.map((item) => [item.x, item.y, item.z]);
    if (validCoordinateData.length !== 0) {
      pointsManager().renderPoints(
        validCoordinateData as THREE.Vector3Tuple[],
        PointEnum.TEMPP,
        undefined,
        2, // 实心圆
        10,
      );
    }
    setNewTableData(newData);
  };

  // 确定按钮
  const handleTableSubmit = async () => {
    const vec3Array = newTableData.map((item) => {
      return new THREE.Vector3(item.x, item.y, item.z).toArray();
    });
    await surfProcess.placePoints({
      surface: formData?.Selection?.source.map((item) => makeId(item)),
      points: vec3Array.flat(),
    });
  };

  return (
    <Box {...props}>
      <>
        <FormContent
          schema={schema}
          extraUiSchema={uiSchema}
          formData={formData}
          fields={{}}
          onChange={(data) => {
            setFormData(data.formData);
          }}
          footerChildren={<></>}
        />
        <ButtonPointsGroups
          onImport={handleImport}
          onExport={handleExport}
          onDeleteAll={handleDeleteAll}
          btnDisabled={newTableData.length === 0}
        />
        <TableComponent
          initialData={uploadTableData}
          onDataChange={handleDataChange}
        />
        <Footer
          onClose={() => {
            pointsManager().removePoints();
            props.onClose();
          }}
          handleSubmit={handleTableSubmit}
          btnDisabled={newTableData.length === 0}
        />
      </>
    </Box>
  );
}
